import pathToRegexp from 'path-to-regexp'

import { getExams } from '../services/indexPage.service'

export default {
  namespace: 'indexPage',
  state: {
    exams: []
  },
  reducers: {
    saveExams(state, action) {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  effects: {
    *getExams(action, { call, put }) {
      const response = yield call(getExams)
      yield put({ type: 'saveExams', payload: { exams: response.data } })
    }
  },
  subscriptions: {
    query({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        const match = pathToRegexp('/').exec(pathname)
        if (match) {
          dispatch({ type: 'getExams' })
        }
      })
    }
  }
}
